import React, { useRef, useEffect, useState } from 'react';
import { PixiCharacter } from '../src/lib';
import {
    AnimationType,
    AnimationParamsMap,
    AnimationConfigItem
} from '../src/types/AnimationParams';

/**
 * 自定义动画配置
 */
const CUSTOM_ANIMATIONS: Record<AnimationType, AnimationConfigItem[]> = {
    wave: [
        { label: '大幅挥手', params: { angle: 0.5, duration: 600, direction: 'right' }, color: '#17a2b8' },
        { label: '小幅挥手', params: { angle: 0.2, duration: 300, direction: 'left' }, color: '#17a2b8' }
    ],
    jump: [
        { label: '高跳双弹', params: { height: 80, duration: 600, bounces: 2 }, color: '#28a745' },
        { label: '轻跳', params: { height: 30, duration: 200, bounces: 1 }, color: '#28a745' }
    ],
    spin: [
        { label: '双圈旋转', params: { rotations: 2, duration: 1500, direction: 'clockwise' }, color: '#fd7e14' },
        { label: '半圈反转', params: { rotations: 0.5, duration: 500, direction: 'counterclockwise' }, color: '#fd7e14' }
    ],
    bounce: [
        { label: '三连弹', params: { height: 50, duration: 500, bounces: 3 }, color: '#e83e8c' },
        { label: '轻弹', params: { height: 20, duration: 200, bounces: 1 }, color: '#e83e8c' }
    ],
    shake: [
        { label: '剧烈摇晃', params: { amount: 20, duration: 500, frequency: 10, axis: 'both' }, color: '#6f42c1' },
        { label: '轻微摇头', params: { amount: 5, duration: 200, frequency: 5, axis: 'x' }, color: '#6f42c1' }
    ],
    scale: [
        { label: '放大脉冲', params: { scale: 1.5, duration: 400, type: 'pulse' }, color: '#20c997' },
        { label: '缩小弹跳', params: { scale: 0.8, duration: 300, type: 'bounce' }, color: '#20c997' }
    ],
    move: [
        { label: '来回移动', params: { x: 100, y: -50, duration: 800, returnToStart: true }, color: '#dc3545' },
        { label: '向上跳跃', params: { x: 0, y: -80, duration: 600, returnToStart: false }, color: '#dc3545' }
    ]
};

/**
 * 外观配置
 */
const APPEARANCE_OPTIONS = {
    body: [
        { label: '身体1', path: './public/assets/body/body1.svg' },
        { label: '身体2', path: './public/assets/body/body2.svg' },
        { label: '身体3', path: './public/assets/body/body3.svg' }
    ],
    clothes: [
        { label: '无衣服', path: '' },
        { label: '红色T恤', path: './public/assets/clothes/shirt1.svg' },
        { label: '绿色连衣裙', path: './public/assets/clothes/shirt2.svg' },
        { label: '蓝色衬衫', path: './public/assets/clothes/shirt3.svg' }
    ],
    hat: [
        { label: '无帽子', path: '' },
        { label: '皇冠', path: './public/assets/hats/hat1.svg' },
        { label: '毛线帽', path: './public/assets/hats/hat2.svg' },
        { label: '棒球帽', path: './public/assets/hats/hat3.svg' }
    ]
};

/**
 * 变换配置
 */
const TRANSFORM_OPTIONS = {
    position: [
        { label: '左上', value: { x: 150, y: 100 } },
        { label: '居中', value: { x: 300, y: 200 } },
        { label: '右下', value: { x: 450, y: 300 } }
    ],
    scale: [
        { label: '缩小', value: { x: 0.5, y: 0.5 } },
        { label: '正常', value: { x: 1, y: 1 } },
        { label: '放大', value: { x: 1.5, y: 1.5 } }
    ],
    rotation: [
        { label: '0°', value: 0 },
        { label: '45°', value: Math.PI / 4 },
        { label: '90°', value: Math.PI / 2 }
    ]
};

/**
 * 简洁演示组件
 * 
 * 展示如何使用优化后的PixiCharacter插件
 * 保持简洁，突出易用性，提供完整的自定义动画参数测试
 * 
 * 手部位置配置示例：
 * - 在CharacterConfig中指定leftHandPosition和rightHandPosition
 * - 位置坐标相对于角色中心点
 * - 如果不指定位置，将使用默认位置
 */
const SimpleDemo: React.FC = () => {
    // ==================== 状态管理 ====================
    const containerRef = useRef<HTMLDivElement>(null);
    const characterRef = useRef<PixiCharacter | null>(null);
    const [isAnimating, setIsAnimating] = useState(false);
    const [isSpeaking, setIsSpeaking] = useState(false);
    const [speechText, setSpeechText] = useState('');
    const [cacheStatus, setCacheStatus] = useState({ cached: 0, total: 0 });
    const [isPreloading, setIsPreloading] = useState(false);


    // ==================== 初始化 ====================
    useEffect(() => {
        if (!containerRef.current || characterRef.current) return;

        // 创建角色实例
        characterRef.current = new PixiCharacter(containerRef.current, {
            width: 600,
            height: 400,
            body: './public/assets/body/body1.svg',
            clothes: './public/assets/clothes/shirt1.svg',
            hat: './public/assets/hats/hat1.svg',
            // 添加手部用于动画测试，并指定位置
            leftHand: './public/assets/hands/left-hand.svg',
            rightHand: './public/assets/hands/right-hand.svg',
            leftHandPosition: { x: -5, y: 5 },  // 自定义左手位置
            rightHandPosition: { x: 5, y: 5 },  // 自定义右手位置
            onAnimationStart: (name: any) => {
                console.log('动画开始:', name);
                setIsAnimating(true);
            },
            onAnimationEnd: (name: any) => {
                console.log('动画结束:', name);
                setIsAnimating(false);
            },
            onSpeechStart: (text: any) => {
                console.log('开始说话:', text);
                setIsSpeaking(true);
            },
            onSpeechEnd: (text: any) => {
                console.log('说话结束:', text);
                setIsSpeaking(false);
            },
            onError: (error: any) => {
                console.error('插件错误:', error);
            }
        });

        // 初始化后预加载所有资源
        preloadAllAssets();



        return () => {
            if (characterRef.current) {
                characterRef.current.destroy();
                characterRef.current = null;
            }
        };
    }, []);

    // ==================== 资源预加载 ====================
    const preloadAllAssets = async () => {
        if (characterRef.current) {
            setIsPreloading(true);
            try {
                setCacheStatus(characterRef.current.getCacheStatus());
            } catch (error) {
                console.warn('预加载失败:', error);
            } finally {
                setIsPreloading(false);
            }
        }
    };

    // ==================== 状态同步 ====================
    useEffect(() => {
        const checkAnimationStatus = () => {
            if (characterRef.current) {
                const currentAnimating = characterRef.current.isAnimating();
                if (currentAnimating !== isAnimating) {
                    setIsAnimating(currentAnimating);
                }
            }
        };

        const interval = setInterval(checkAnimationStatus, 100);
        return () => clearInterval(interval);
    }, [isAnimating]);

    // ==================== 动画控制 ====================
    /**
     * 执行基础动画
     */
    const handleAnimation = async (animation: string) => {
        if (!characterRef.current || isAnimating) return;

        try {
            switch (animation) {
                case 'wave': await characterRef.current.wave(); break;
                case 'jump': await characterRef.current.jump(); break;
                case 'spin': await characterRef.current.spin(); break;
                case 'bounce': await characterRef.current.bounce(); break;
                case 'shake': await characterRef.current.shake(); break;
            }
        } catch (error) {
            console.error('动画执行失败:', error);
        }
    };

    /**
     * 执行自定义参数动画
     */
    const handleCustomAnimation = async <T extends AnimationType>(
        animation: T,
        params: AnimationParamsMap[T]
    ) => {
        if (!characterRef.current || isAnimating) return;

        try {
            switch (animation) {
                case 'wave': await characterRef.current.wave(params); break;
                case 'jump': await characterRef.current.jump(params); break;
                case 'spin': await characterRef.current.spin(params); break;
                case 'bounce': await characterRef.current.bounce(params); break;
                case 'shake': await characterRef.current.shake(params); break;
                case 'scale': await characterRef.current.scale(params); break;
                case 'move': await characterRef.current.move(params); break;
            }
        } catch (error) {
            console.error('自定义动画执行失败:', error);
        }
    };

    /**
     * 停止动画
     */
    const handleStop = () => {
        characterRef.current?.stop();
        setIsAnimating(false);
    };



    /**
     * 重置角色状态
     */
    const handleReset = () => {
        characterRef.current?.reset();
        setIsAnimating(false);
    };

    // ==================== 语音控制 ====================
    /**
     * 开始说话
     */
    const handleSpeak = async () => {
        if (!characterRef.current || isSpeaking || !speechText.trim()) return;

        try {
            await characterRef.current.speak(speechText);
        } catch (error) {
            console.error('说话失败:', error);
        }
    };

    /**
     * 停止说话
     */
    const handleStopSpeaking = () => {
        characterRef.current?.stopSpeaking();
        setIsSpeaking(false);
    };

    // ==================== 资源管理 ====================
    /**
     * 预加载所有资源
     */
    const handlePreloadAll = async () => {
        if (!characterRef.current || isPreloading) return;

        setIsPreloading(true);
        try {
            const allAssets = [
                './public/assets/body/body1.svg',
                './public/assets/body/body2.svg',
                './public/assets/body/body3.svg',
                './public/assets/clothes/shirt1.svg',
                './public/assets/clothes/shirt2.svg',
                './public/assets/clothes/shirt3.svg',
                './public/assets/hats/hat1.svg',
                './public/assets/hats/hat2.svg',
                './public/assets/hats/hat3.svg'
            ];
            await characterRef.current.preloadAll(allAssets);
            setCacheStatus(characterRef.current.getCacheStatus());
        } catch (error) {
            console.error('预加载失败:', error);
        } finally {
            setIsPreloading(false);
        }
    };

    /**
     * 预加载自定义资源
     */
    const handlePreloadCustom = async () => {
        if (!characterRef.current || isPreloading) return;

        setIsPreloading(true);
        try {
            const customAssets = [
                './public/assets/body/body1.svg',
                './public/assets/clothes/shirt1.svg',
                './public/assets/hats/hat1.svg'
            ];
            await characterRef.current.preloadAll(customAssets);
            setCacheStatus(characterRef.current.getCacheStatus());
        } catch (error) {
            console.error('预加载失败:', error);
        } finally {
            setIsPreloading(false);
        }
    };

    // ==================== 外观控制 ====================
    /**
     * 改变外观
     */
    const handleAppearance = async (type: string, path: string) => {
        if (!characterRef.current) return;

        try {
            switch (type) {
                case 'body': await characterRef.current.setBody(path); break;
                case 'clothes': await characterRef.current.setClothes(path); break;
                case 'hat': await characterRef.current.setHat(path); break;
            }
        } catch (error) {
            console.error('外观设置失败:', error);
        }
    };

    // ==================== 变换控制 ====================
    /**
     * 设置变换
     */
    const handleTransform = (type: string, value: number | { x: number; y: number }) => {
        if (!characterRef.current) return;

        switch (type) {
            case 'position':
                if (typeof value === 'object') {
                    characterRef.current.setPosition(value.x, value.y);
                }
                break;
            case 'scale':
                if (typeof value === 'object') {
                    characterRef.current.setScale(value.x, value.y);
                }
                break;
            case 'rotation':
                if (typeof value === 'number') {
                    characterRef.current.setRotation(value);
                }
                break;
        }
    };

    // ==================== 通用按钮组件 ====================
    /**
     * 渲染按钮组件
     */
    const renderButton = (
        label: string,
        onClick: () => void,
        disabled: boolean = false,
        color: string = '#007bff',
        size: 'normal' | 'small' = 'normal'
    ) => (
        <button
            onClick={onClick}
            disabled={disabled}
            style={{
                padding: size === 'small' ? '6px 12px' : '8px 16px',
                border: 'none',
                borderRadius: '4px',
                background: disabled ? '#6c757d' : color,
                color: 'white',
                cursor: disabled ? 'not-allowed' : 'pointer',
                fontSize: size === 'small' ? '12px' : '14px'
            }}
        >
            {label}
        </button>
    );

    /**
     * 渲染控制组
     */
    const renderControlGroup = (title: string, children: React.ReactNode) => (
        <div style={{ marginBottom: '20px' }}>
            <h4 style={{ margin: '0 0 10px 0', color: '#333' }}>{title}</h4>
            <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                {children}
            </div>
        </div>
    );

    // ==================== 渲染 ====================
    return (
        <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
            <h2 style={{ color: '#333', marginBottom: '10px' }}>PixiJS角色插件 - 完整演示</h2>
            <p style={{ color: '#666', marginBottom: '20px' }}>
                展示PixiCharacter插件的所有功能，包括自定义动画参数、外观控制、语音合成等
            </p>

            <div style={{ display: 'flex', gap: '20px' }}>
                {/* 渲染区域 */}
                <div style={{ flex: 1 }}>
                    <h3 style={{ color: '#333', marginBottom: '10px' }}>渲染区域</h3>
                    <div
                        ref={containerRef}
                        style={{
                            width: '600px',
                            height: '400px',
                            border: '2px solid #333',
                            borderRadius: '8px',
                            overflow: 'hidden',
                            background: '#f8f9fa'
                        }}
                    />
                </div>

                {/* 控制面板 */}
                <div style={{ flex: 1 }}>
                    <h3 style={{ color: '#333', marginBottom: '15px' }}>控制面板</h3>

                    {/* 状态显示 */}
                    <div style={{
                        padding: '15px',
                        background: '#f8f9fa',
                        borderRadius: '8px',
                        marginBottom: '20px',
                        border: '1px solid #dee2e6'
                    }}>
                        <div style={{ marginBottom: '5px' }}>
                            <strong>状态:</strong> {isAnimating ? '🔄 动画中' : '✅ 空闲'}
                        </div>
                        <div style={{ marginBottom: '5px' }}>
                            <strong>说话:</strong> {isSpeaking ? '🗣️ 说话中' : '✅ 空闲'}
                        </div>

                        <div style={{ marginBottom: '5px' }}>
                            <strong>缓存:</strong> {cacheStatus.cached}/{cacheStatus.total} 个资源
                        </div>
                        {isPreloading && (
                            <div style={{ color: '#007bff', fontWeight: 'bold' }}>
                                ⏳ 预加载中...
                            </div>
                        )}
                    </div>

                    {/* 基础动画控制 */}
                    {renderControlGroup('基础动画', (
                        <>
                            {['wave', 'jump', 'spin', 'bounce', 'shake'].map(animation => (
                                renderButton(
                                    animation,
                                    () => handleAnimation(animation),
                                    isAnimating,
                                    '#007bff'
                                )
                            ))}
                            {renderButton('停止', handleStop, !isAnimating, '#dc3545')}
                            {renderButton('复原', handleReset, false, '#ffc107', 'normal')}
                        </>
                    ))}



                    {/* 手部动画测试 */}
                    <div style={{ marginBottom: '20px' }}>
                        <h4 style={{ margin: '0 0 15px 0', color: '#333' }}>手部动画测试</h4>
                        <div style={{
                            background: '#e3f2fd',
                            padding: '15px',
                            borderRadius: '8px',
                            border: '1px solid #2196f3'
                        }}>
                            <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                                {renderButton('左手挥手', () => handleCustomAnimation('wave', { direction: 'left', angle: 0.4 }), isAnimating, '#ff9800')}
                                {renderButton('右手挥手', () => handleCustomAnimation('wave', { direction: 'right', angle: 0.4 }), isAnimating, '#ff9800')}
                            </div>
                            <div style={{ marginTop: '10px', padding: '10px', background: '#fff3e0', borderRadius: '4px', border: '1px solid #ffb74d' }}>
                                <p style={{ margin: '0 0 8px 0', fontSize: '12px', color: '#e65100' }}>
                                    🔧 手部位置调整测试 (位置通过配置传入)
                                </p>
                                <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                                    {renderButton('左手向上', () => characterRef.current?.setHandPosition('left', -30, -35), false, '#4caf50', 'small')}
                                    {renderButton('左手向下', () => characterRef.current?.setHandPosition('left', -30, -15), false, '#4caf50', 'small')}
                                    {renderButton('右手向上', () => characterRef.current?.setHandPosition('right', 30, -35), false, '#4caf50', 'small')}
                                    {renderButton('右手向下', () => characterRef.current?.setHandPosition('right', 30, -15), false, '#4caf50', 'small')}
                                    {renderButton('重置位置', () => {
                                        characterRef.current?.setHandPosition('left', -5, 5);
                                        characterRef.current?.setHandPosition('right', 5, 5);
                                    }, false, '#ff5722', 'small')}

                                </div>
                            </div>
                        </div>
                    </div>

                    {/* 自定义动画参数 */}
                    <div style={{ marginBottom: '20px' }}>
                        <h4 style={{ margin: '0 0 15px 0', color: '#333' }}>自定义动画参数</h4>
                        <div style={{
                            background: '#f8f9fa',
                            padding: '20px',
                            borderRadius: '8px',
                            border: '1px solid #dee2e6'
                        }}>
                            {Object.entries(CUSTOM_ANIMATIONS).map(([animationType, animations]) => (
                                <div key={animationType} style={{ marginBottom: '20px' }}>
                                    <h5 style={{
                                        margin: '0 0 10px 0',
                                        color: '#495057',
                                        textTransform: 'capitalize',
                                        fontSize: '14px',
                                        fontWeight: 'bold'
                                    }}>
                                        {animationType} 动画
                                    </h5>
                                    <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                                        {animations.map(({ label, params, color }) => (
                                            renderButton(
                                                label,
                                                () => handleCustomAnimation(animationType as AnimationType, params),
                                                isAnimating,
                                                color,
                                                'small'
                                            )
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* 外观控制 */}
                    {renderControlGroup('外观控制', (
                        <>
                            {Object.entries(APPEARANCE_OPTIONS).map(([type, options]) => (
                                <div key={type} style={{ width: '100%', marginBottom: '10px' }}>
                                    <h5 style={{
                                        margin: '0 0 8px 0',
                                        color: '#495057',
                                        textTransform: 'capitalize',
                                        fontSize: '12px'
                                    }}>
                                        {type}
                                    </h5>
                                    <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                                        {options.map(({ label, path }) => (
                                            renderButton(
                                                label,
                                                () => handleAppearance(type, path),
                                                false,
                                                '#6c757d',
                                                'small'
                                            )
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </>
                    ))}

                    {/* 性能优化 */}
                    {renderControlGroup('性能优化', (
                        <>
                            {renderButton(
                                isPreloading ? '预加载中...' : '预加载全部资源',
                                handlePreloadAll,
                                isPreloading,
                                '#17a2b8'
                            )}
                            {renderButton(
                                isPreloading ? '预加载中...' : '预加载部分资源',
                                handlePreloadCustom,
                                isPreloading,
                                '#28a745'
                            )}
                        </>
                    ))}

                    {/* 说话控制 */}
                    <div style={{ marginBottom: '20px' }}>
                        <h4 style={{ margin: '0 0 10px 0', color: '#333' }}>说话控制</h4>
                        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
                            <input
                                type="text"
                                value={speechText}
                                onChange={(e) => setSpeechText(e.target.value)}
                                placeholder="输入要说的话..."
                                style={{
                                    padding: '8px 12px',
                                    border: '1px solid #ccc',
                                    borderRadius: '4px',
                                    flex: 1,
                                    minWidth: '200px',
                                    fontSize: '14px'
                                }}
                            />
                            {renderButton(
                                '说话',
                                handleSpeak,
                                isSpeaking || !speechText.trim(),
                                '#28a745'
                            )}
                            {renderButton(
                                '停止说话',
                                handleStopSpeaking,
                                !isSpeaking,
                                '#dc3545'
                            )}
                        </div>
                    </div>

                    {/* 变换控制 */}
                    {Object.entries(TRANSFORM_OPTIONS).map(([transformType, options]) => (
                        <div key={transformType} style={{ marginBottom: '15px' }}>
                            <h4 style={{
                                margin: '0 0 10px 0',
                                color: '#333',
                                textTransform: 'capitalize',
                                fontSize: '14px'
                            }}>
                                {transformType} 变换
                            </h4>
                            <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                                {options.map(({ label, value }) => (
                                    renderButton(
                                        label,
                                        () => handleTransform(transformType, value),
                                        false,
                                        '#6f42c1',
                                        'small'
                                    )
                                ))}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default SimpleDemo; 